package Web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {
    private static final String SERVER_IP = "127.0.0.1";  // 服务器IP地址，这里假设是本地
    private static final int SERVER_PORT = 8888;  // 服务器端口号

    public static void main(String[] args) {
        // 使用Socket连接到指定的服务器 IP 和端口
        try (Socket socket = new Socket(InetAddress.getByName(SERVER_IP), SERVER_PORT)) {
            System.out.println("已连接到服务器: " + socket.getInetAddress());
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("请输入要发送的数据（输入exit退出）: ");
                String input = scanner.nextLine();
                if ("exit".equalsIgnoreCase(input)) {
                    break;
                }
                // 向服务器发送数据
                outputStream.write(input.getBytes());
                // 强制将缓冲区数据输出到网络
                outputStream.flush();
                byte[] buffer = new byte[1024];
                int length = inputStream.read(buffer);
                String response = new String(buffer, 0, length);
                System.out.println("服务器响应: " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
